﻿@page "/config"
@layout EmptyLayout
@inject Task<HttpClient> tHttp

<div style="width: 320px;
    margin: auto auto;
    margin-top: 20%;">

    <h3>Login</h3>
    <Space Direction="@DirectionVHType.Vertical" Style="width:320px;">
        <SpaceItem Style="width:320px;">
            <AntDesign.Input AutoFocus="true"
                             Placeholder="please input base path"
                             OnPressEnter="()=>SetToken()"
            Size="large" @bind-Value="@basePath" Type="text">
                <Prefix>
                    <Icon Type="diff" Theme="outline" />
                </Prefix>
            </AntDesign.Input>
        </SpaceItem>
        <SpaceItem Style="width:320px;">
            <AntDesign.Input 
            Placeholder="please input token" 
            Size="large" @bind-Value="@token"
                             OnPressEnter="()=>SetToken()"
                             Type="text">
                <Prefix><Icon Type="lock" /></Prefix>
            </AntDesign.Input>
        </SpaceItem>
        <SpaceItem Style="width:320px;">
            <Spin Spinning="Loading" Size="large" Tip="验证中...">
                <Button Type="primary" @onclick="() => SetToken()" Class="submit" Size="large" Block>提&nbsp;交</Button>
            </Spin>
        </SpaceItem>
    </Space>
    </div>



@code {
    public string basePath { get; set; }
    public string token { get; set; }
    bool Loading { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await js.InvokeVoidAsync("eval", "document.title='Config'");
        await base.OnAfterRenderAsync(firstRender);
    }

    async Task SetToken()
    {
        if (string.IsNullOrWhiteSpace(token))
        {
            _message.Error("token is null");
            return;
        }

        if (string.IsNullOrWhiteSpace(basePath))
        {
            _message.Error("basePath is null");
            return;
        }

        Loading = true;
        var Http = await tHttp;
        var result = await Http.PostAsJsonAsync("/token", new Config
        {
                token = token,
                basePath = basePath
        });
        var content = await result.Content.ReadAsStringAsync();

        if (content == "ok")
        {
            await js.InvokeVoidAsync("localStorage.setItem", "token", token);
            navigationManager.NavigateTo("/");
        }
        else
        {
            Loading = false;
            _ = _message.Error(content);
        }
        StateHasChanged();
    }
}
